using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;

using Infragistics.Windows.DataPresenter;

using RadioPlayerAddIn.Properties;

using ViewOnCore;
using ViewOnCore.Helper.WPF;
using ViewOnCore.Helper.Collection;
using ViewOnCore.Device;
using ViewOnCore.HostContract.Media;
using ViewOnCore.HostContract;
using ViewOnCore.Helper.Process;
using ViewOnCore.Visual;

namespace RadioPlayerAddIn
{

    /// <summary>
    /// This player manage the online radios list.
    /// </summary>
    public partial class RadioPlayer : VisualPart
    {

        #region Variables

        private bool _isLoaded = false;

        #endregion

        #region Constructor

        public RadioPlayer()
        {
            InitializeComponent();

            MediaTypeTags.Add("Radio");

            btnRemoveRadio.IsEnabled = false;
            btnEditRadio.IsEnabled = false;

            btnAddRadio.Click += new RoutedEventHandler(btnAddRadio_Click);
            btnRemoveRadio.Click += new RoutedEventHandler(btnRemoveRadio_Click);
            btnEditRadio.Click += new RoutedEventHandler(btnEditRadio_Click);

            Host.MediaService.MediaDeviceActivation += new EventHandler(MediaService_MediaDeviceActivation);
            Host.MediaService.MediaConnected += new EventHandler(MediaService_MediaDataConnected);
            Host.MediaService.MediaCannotConnect += new EventHandler(MediaService_MediaDataCannotConnect);
            Host.HostCommand += new HostCommandEventHandler(Host_HostCommand);

            xdgGenres.KeyUp += new KeyEventHandler(xdgGenres_KeyUp);
            xdgGenres.MouseDoubleClick += new MouseButtonEventHandler(xdgGenres_MouseDoubleClick);
            xdgGenres.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(xdgGenres_PreviewMouseLeftButtonDown);
            xdgGenres.PreviewMouseRightButtonDown += new MouseButtonEventHandler(xdgGenres_PreviewMouseRightButtonDown);
            xdgGenres.SelectedItemsChanged += new EventHandler<Infragistics.Windows.DataPresenter.Events.SelectedItemsChangedEventArgs>(xdgGenres_SelectedItemsChanged);
        }

        #endregion

        #region Properties

        override public string Handle
        {
            get
            {
                return "ViewOnTv_RadioPlayerAddIn";
            }
        }

        #endregion

        #region VisualPart : management

        override public VisualPartDisplayInformation OnRequestDisplayInformation(VisualPartDisplayInformation currentDisplayInformation, VisualPartDisplayInformation leavedDisplayInformation)
        {
            VisualPartDisplayInformation newDisplayInformation = new VisualPartDisplayInformation();

            newDisplayInformation.WindowState = WindowState.Normal;

            return newDisplayInformation;
        }

        override public VisualPartPriority OnRequestVisualPartPriority()
        {
            if (Host.VisualService.VisualPartMode != VisualPartMode.Normal)
                return VisualPartPriority.None;

            if (Host.MediaService.CurrentMediaDeviceFeature.MediaTypeTags.Contains("Radio"))
                return VisualPartPriority.Normal;

            return VisualPartPriority.None;
        }

        #endregion

        #region Device Activation

        void MediaService_MediaDeviceActivation(object sender, EventArgs e)
        {
            if (_isLoaded)
                return;

            if (!VisualPartHelper.IsCurrentMediaDeviceSupported(this.MediaTypeTags))
                return;

            _isLoaded = true;

            //---- Set up the radios list
            //xdgGenres.DataSource = null;
            xdgGenres.DataSource = Host.MediaService.CurrentMediaDeviceFeature.MediaDatas;
        }

        #endregion

        #region SelectedItemsChanged

        void xdgGenres_SelectedItemsChanged(object sender, Infragistics.Windows.DataPresenter.Events.SelectedItemsChangedEventArgs e)
        {
            if (xdgGenres.SelectedItems.Records.Count < 1)
            {
                btnRemoveRadio.IsEnabled = false;
                btnEditRadio.IsEnabled = false;
                return;
            }

            Radio radio = ((DataRecord)xdgGenres.SelectedItems.Records[0]).DataItem as Radio;
            if (radio == null)
            {
                btnRemoveRadio.IsEnabled = false;
                btnEditRadio.IsEnabled = false;
                return;
            }

#if !IS_ADMINISTRATIVE_MODE
            if (radio.Source == RadioSource.ViewOnTv)
            {
                btnRemoveRadio.IsEnabled = false;
                btnEditRadio.IsEnabled = false;
                return;
            }
#endif

            btnRemoveRadio.IsEnabled = true;
            btnEditRadio.IsEnabled = true;
        }

        #endregion

        #region PlaySelectedRadio

        private void PlaySelectedRadio()
        {
            if (xdgGenres.SelectedItems.Records.Count < 1)
                return;

            Radio radio = ((DataRecord)xdgGenres.SelectedItems.Records[0]).DataItem as Radio;

            if (radio == null)
                return;

            txtCannotConnect.Visibility = Visibility.Hidden;
            Host.MediaService.PlayMedia(radio);
        }

        #endregion

        #region RemoveSelectedRadio

        private void RemoveSelectedRadio()
        {
            string message = Globalization.RadioPart_RemoveSelectedRadio_Message1;
            string message2 = Globalization.RadioPart_RemoveSelectedRadio_Message2;

            QuestionDialog dialog = new QuestionDialog(QuestionDialog.QuestionDialogType.YesNo, message, message2, null, null, 350);
            dialog.ShowDialog(Host.ApplicationDesktop,
                                                new ChildWindowDialogClosedHandler(OnConfirmRemoveRadioDialogClosed));
        }

        private void OnConfirmRemoveRadioDialogClosed(ChildWindowDecorator window)
        {
            QuestionDialog dialog = window.Parent as QuestionDialog;

            if (!dialog.IsOkYes)
                return;

            Radio radio = ((DataRecord)xdgGenres.SelectedItems.Records[0]).DataItem as Radio;

            //---- Add the radio
            List<MediaData> medias = new List<MediaData>();
            medias.Add(radio);

            Host.MediaService.RemoveMediaDatas(medias,
                Host.MediaService.CurrentMediaDeviceFeature,
                Host.MediaService.CurrentMediaDeviceFeatureItem,
                null);
        }

        #endregion

        #region EditSelectedRadio

        private void EditSelectedRadio()
        {
            // To avoid a Bug ! But should not occured !! Strange !!
            if (xdgGenres.SelectedItems.Records.Count < 1)
                return;

            Radio radio = ((DataRecord)xdgGenres.SelectedItems.Records[0]).DataItem as Radio;
            EditRadioDialog dialog = new EditRadioDialog(radio);

            dialog.ShowDialog(Host.ApplicationDesktop,
                                                new ChildWindowDialogClosedHandler(OnEditRadioDialogClosed));
        }

        private void OnEditRadioDialogClosed(ChildWindowDecorator window)
        {
            EditRadioDialog dialog = window.Parent as EditRadioDialog;

            if (!dialog.IsOk)
                return;

            //---- Update the radio
            List<MediaData> medias = new List<MediaData>(1);
            medias.Add(dialog.Radio);
            Host.MediaService.CurrentMediaDeviceFeature.UpdateTag(medias, MediaDataTagField.All, null);
        }

        #endregion

        #region Double click - play

        void xdgGenres_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            PlaySelectedRadio();
        }

        void MediaService_MediaDataCannotConnect(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (DelegateInvoker)delegate { txtCannotConnect.Visibility = Visibility.Visible; });
        }

        void MediaService_MediaDataConnected(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (DelegateInvoker)delegate { txtCannotConnect.Visibility = Visibility.Hidden; });
        }

        #endregion

        #region Clik on link

        void xdgGenres_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DependencyObject source = e.OriginalSource as DependencyObject;

            if (source == null) return;
            CellValuePresenter cvp = Infragistics.Windows.Utilities.GetAncestorFromType(source, typeof(CellValuePresenter), true) as CellValuePresenter;

            if (cvp == null)
                return;
            if (cvp.Field.Name == "SiteUrl")
            {
                ProcessHelper.OpenUrl((string)cvp.Content);

                // do stuff here
                e.Handled = true;
            }
        }

        #endregion

        #region ContextMenu

        void xdgGenres_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (xdgGenres.SelectedItems.Records.Count < 1)
                return;

#if IS_ADMINISTRATIVE_MODE
			ContextMenu menu = (ContextMenu)FindResource("RadioPartContextMenuExtended");
#else
            ContextMenu menu;
            Radio radio = ((DataRecord)xdgGenres.SelectedItems.Records[0]).DataItem as Radio;
            if (radio == null)
                return;

            if (radio.Source == RadioSource.User)
                menu = (ContextMenu)FindResource("RadioPartContextMenu");
            else
                menu = (ContextMenu)FindResource("RadioPartContextMenuExtended");
#endif

            menu.IsOpen = true;
            e.Handled = true;
        }

        void contextMenuPlay_Click(object sender, RoutedEventArgs e)
        {
            PlaySelectedRadio();
        }

        void contextMenuRemove_Click(object sender, RoutedEventArgs e)
        {
            RemoveSelectedRadio();
        }

        void contextMenuEdit_Click(object sender, RoutedEventArgs e)
        {
            EditSelectedRadio();
        }

        #endregion

        #region Button event : Add

        public void btnAddRadio_Click(object sender, RoutedEventArgs args)
        {
            EditRadioDialog dialog = new EditRadioDialog(null);
            dialog.ShowDialog(Host.ApplicationDesktop,
                                                new ChildWindowDialogClosedHandler(OnAddRadioDialogClosed));
        }

        #endregion

        #region Button event : Remove

        public void btnRemoveRadio_Click(object sender, RoutedEventArgs args)
        {
            RemoveSelectedRadio();
        }

        #endregion

        #region Button event : Edit

        public void btnEditRadio_Click(object sender, RoutedEventArgs args)
        {
            EditSelectedRadio();
        }

        #endregion

        #region Keyboard : Remove

        void xdgGenres_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Delete)
                return;

            RemoveSelectedRadio();
        }

        #endregion

        #region On... DialogClosed

        private void OnAddRadioDialogClosed(ChildWindowDecorator window)
        {
            EditRadioDialog dialog = window.Parent as EditRadioDialog;

            if (!dialog.IsOk)
                return;

            //---- Add the radio
            Host.MediaService.CurrentMediaDeviceFeature.AddMediaData(null, dialog.Radio, true);
        }

        #endregion

        #region Host : HostCommand

        void Host_HostCommand(object sender, string commandId, params object[] parameters)
        {
            if (Host.VisualService.VisualPartMode != VisualPartMode.Normal)
                return;

            if (commandId == HostCommandIds.PlayMediaData && parameters[0] is Radio)
            {
                //---- Activate the right device
                MediaDevice device = Host.MediaService.FindDeviceByHandle("MyLibrary");
                MediaFeature feature = device.FindMediaFeature("Radio");

                Host.MediaService.ActivateMediaDevice(device, feature, null);

                //---- Play
                Radio radio = (Radio)parameters[0];
                Host.MediaService.PlayMedia(radio);
            }
        }

        #endregion

    }

}